# -*- coding: utf-8 -*-

import json
import requests
from requests import exceptions

URL = 'https://api.github.com'

def build_uri(endpoint):
    return '/'.join([URL, endpoint])

def better_print(json_str):
    return json.dumps(json.loads(json_str), indent=4)

# 无参数的请求
def request_method():
    #response = requests.get(build_uri('users/shfanzie'))
    #print better_print(response.text)

    response = requests.get(build_uri('user/emails'), auth=('shfanzie', '**********'))  #需要授权的请求
    print response.text
    print better_print(response.text)

# 带参数的请求
def params_request():
    response = requests.get(build_uri('users'), params={'since': 11})
    print better_print(response.text)
    print response.request.headers
    print response.url

# 请求异常处理
def time_request():
    try:
        response = requests.get(build_uri('user/emails'), auth=('shfanzie', '**********'), timeout=10)
        response.raise_for_status()
    except exceptions.Timeout as e:
        print e.message
    except exceptions.HTTPError as e:
        print e.message
    else:
        print response.text
        print response.status_code

# 自定义Request
def hard_requests():
    from requests import Request, Session
    s = Session()
    headers = {'User-Agent': 'fake1.3.4'}
    req = Request('GET', build_uri('user/emails'), auth=('shfanzie', '**********'), headers = headers)
    prepped = req.prepare()
    print prepped.body
    print prepped.headers
    
    try:
        resp = s.send(prepped, timeout=1)
        resp.raise_for_status()
    except exceptions.Timeout as e:
        print e.message
    except exceptions.HTTPError as e:
        print e.message
    else:
        print resp.status_code
        print resp.reason
        print resp.request.headers
        print resp.text

if __name__ == '__main__':
    hard_requests()
